<!-- eslint-disable sort-imports -->
<script lang="jsx" setup>
import { getCurrentInstance, ref, watch, computed } from 'vue';
import { message, Input } from 'ant-design-vue';
import Modal from '@/components/common/modal.vue';
import underReview from '@/assets/imgs/examine-icon/under-review.png';
import unaudited from '@/assets/imgs/examine-icon/unaudited.png';
import audited from '@/assets/imgs/examine-icon/audited.png';
import { newtoolInformation, toolinformationEdit } from '@/service/api/modules/cut/v-cut';
import { get } from '@/service/api/api';
import { isNonNegativeInteger } from '@/utils';

import { useAuthStore } from '@/store/modules/auth';

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => false
  },
  operateType: {
    type: String,
    default: 'add'
  },
  rowData: {
    type: Object,
    default: null
  }
});

const instance = getCurrentInstance();
const authStore = useAuthStore();
const fqcArea = ref(0);
const emit = defineEmits(['addModalClose', 'addSuccess']);

const topFormList = ref([
  {
    type: 'tabs',
    span: 24,
    name: '状态信息'
  },
  {
    type: 'datePicker',
    key: 'useDate',
    label: '使用时间',
    span: 6,
    rule: {
      required: true,
      message: '请选择使用时间',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'operator',
    label: '操作员',
    defaultValue: authStore.userInfo.user.nickName || authStore.userInfo.user.userName,
    disabled: true,
    span: 6
  },
  {
    type: 'input',
    key: 'foreman',
    label: '领班审核',
    disabled: true,
    span: 6
  },
  {
    type: 'input',
    key: 'examiner',
    label: '主管审核',
    disabled: true,
    span: 6
  }
]);
// 公用数据列表
const commomColumns = [
  {
    key: 'knifeLib',
    dataIndex: 'knifeLib',
    title: '刀组',
    width: 50,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'knifeNum1',
    dataIndex: 'knifeNum1',
    title: '刀具上编号',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (props.operateType === 'add') {
        return record.knifes?.knifeNum1;
      }
      return record?.knifeNum1;
    }
  },
  {
    key: 'knifeNum2',
    dataIndex: 'knifeNum2',
    title: '刀具下编号',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (props.operateType === 'add') {
        return record.knifes?.knifeNum2;
      }
      return record?.knifeNum2;
    }
  },
  {
    key: 'knifeDiameter1',
    dataIndex: 'knifeDiameter1',
    title: '刀具直径1(mm)',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (props.operateType === 'add') {
        return record.knifes?.knifeDiameter1;
      }
      return record?.knifeDiameter1;
    }
  },
  {
    key: 'knifeDiameter2',
    dataIndex: 'knifeDiameter2',
    title: '刀具直径2(mm)',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (props.operateType === 'add') {
        return record.knifes?.knifeDiameter2;
      }
      return record?.knifeDiameter2;
    }
  }
];

const columns = computed(() => {
  if (props.operateType === 'add') {
    return [
      ...commomColumns,
      {
        key: 'useDateTotalLength',
        dataIndex: 'useDateTotalLength',
        title: '今日累计行程(m)',
        align: 'center',
        width: 100,
        checked: true,
        ellipsis: true,
        customRender: ({ record }) => {
          if (props.operateType === 'look') {
            return <div style="min-width:150px">{record.useDateTotalLength}</div>;
          }
          return (
            <Input
              style="height: 22px !important;"
              value={record.useDateTotalLength}
              onChange={e => {
                const value = e.target.value;
                record.useDateTotalLength = Number(value);
              }}
              onBlur={e => {
                const value = e.target.value;
                if (!(isNonNegativeInteger(Number(value).toString()) && Number(value >= 0))) {
                  message.error('请输入正整数');
                  record.useDateLength = null;
                  return;
                }
                record.useDateTotalLength = Number(value);
              }}
            ></Input>
          );
        }
      },
      {
        key: 'useTotalLength',
        dataIndex: 'useTotalLength',
        title: '累计行程(m)',
        width: 100,
        align: 'center',
        checked: true,
        ellipsis: true,
        customRender: ({ record }) => {
          if (props.operateType) {
            return record.knifes?.useTotalLength;
          }
          return record?.useTotalLength;
        }
      },
      {
        key: 'grind',
        dataIndex: 'grind',
        title: '研磨',
        width: 100,
        align: 'center',
        checked: true,
        ellipsis: true,
        customRender: ({ record }) => {
          if (props.operateType === 'look') {
            return <div style="min-width:150px">{record.grind}</div>;
          }
          return (
            <Input
              style="height: 22px !important;"
              value={record.grind}
              onChange={e => {
                const value = e.target.value;
                record.grind = Number(value);
              }}
              onBlur={e => {
                const value = e.target.value;
                if (!(isNonNegativeInteger(Number(value).toString()) && Number(value >= 0))) {
                  message.error('请输入正整数');
                  record.grind = null;
                  return;
                }
                record.grind = Number(value);
              }}
            ></Input>
          );
        }
      }
    ];
  }
  return [
    ...commomColumns,
    {
      key: 'useDateTotalLength',
      dataIndex: 'useDateTotalLength',
      title: '累计行程(m)',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true,
      customRender: ({ record }) => {
        if (props.operateType === 'look') {
          return <div style="min-width:150px">{record.useDateTotalLength}</div>;
        }
        return (
          <Input
            style="height: 22px !important;"
            value={record.useDateTotalLength}
            onChange={e => {
              const value = e.target.value;
              record.useDateTotalLength = Number(value);
            }}
            onBlur={e => {
              const value = e.target.value;
              if (!(isNonNegativeInteger(Number(value).toString()) && Number(value >= 0))) {
                message.error('请输入正整数');
                record.useDateTotalLength = null;
                return;
              }
              record.useDateTotalLength = Number(value);
            }}
          ></Input>
        );
      }
    },
    {
      key: 'useDateLength',
      dataIndex: 'useDateLength',
      title: '今日实际行程(m)',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true,
      customRender: ({ record }) => {
        return record?.useDateLength;
      }
    },
    {
      key: 'grind',
      dataIndex: 'grind',
      title: '研磨',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true,
      customRender: ({ record }) => {
        if (props.operateType === 'look') {
          return <div style="min-width:150px">{record.grind}</div>;
        }
        return (
          <Input
            style="height: 22px !important;"
            value={record.grind}
            onChange={e => {
              const value = e.target.value;
              record.grind = Number(value);
            }}
            onBlur={e => {
              const value = e.target.value;
              if (!(isNonNegativeInteger(Number(value).toString()) && Number(value >= 0))) {
                message.error('请输入正整数');
                record.grind = null;
                return;
              }
              record.grind = Number(value);
            }}
          ></Input>
        );
      }
    }
  ];
});

const knifeData = ref([]);
const loading = ref(false);

const modelVisible = ref(props.visible);
const modleAddLoading = ref(false);

const topFormRef = ref(null);
const toptopFormRef = ref(null);

const model = ref(getModel(topFormList.value));

function getModel(arr) {
  const obj = {};
  arr.forEach(item => {
    obj[item.key] = item.defaultValue || null;
    if (props?.rowData) {
      obj[item.key] = props?.rowData?.[item.key];
    }
    if (item.tansfromDisabled) {
      item.disabled = item.tansfromDisabled(props.operateType);
    }
  });
  console.log('obj :>> ', obj);
  return obj;
}

// 获取刀具信息数据
function getKnifeData() {
  loading.value = true;
  let params = {};
  if (props.rowData) {
    params = { ...props.rowData };
  }
  get('qms/single/singleVcutKnifes/selectMateList', params)
    .then(({ data, error }) => {
      if (!error) {
        data.forEach((item, index) => {
          item.index = index + 1;
        });
        knifeData.value = data;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

async function handleOk() {
  const form = { ...topFormRef.value, ...toptopFormRef.value };
  const badDoList = knifeData.value.map(item => {
    item.updateDate = model.value.updateDate;
    item.updateBy = '';
    // 修改之后数据的返回
    return {
      ...item.knifes,
      ...model.value,
      ...item,
      useDate: model.value.useDate,
      id: props.operateType === 'add' ? undefined : props.rowData.id
    };
  });
  await form.validateForm();
  const msgObj = {
    add: '新增',
    edit: '修改'
  };
  let pro;
  if (props.rowData) {
    pro = toolinformationEdit(badDoList[0]);
  } else {
    pro = newtoolInformation(badDoList);
  }
  modleAddLoading.value = true;

  pro
    .then(({ error }) => {
      if (!error) {
        message.success(`${msgObj[props.operateType]}成功`);
        const obj = { ...instance.parent.refs.commonSearchRef, ...instance.parent.refs.tableRef };
        obj.formReset();
        obj.tableSelectChange([]);
        handleClose();
      }
    })
    .finally(() => {
      modleAddLoading.value = false;
    });
}

function handleClose() {
  modelVisible.value = false;
  fqcArea.value = null;
  model.value = getModel(topFormList.value);
  emit('addModalClose');
}

watch(
  () => props.visible,
  val => {
    modelVisible.value = val;
    if (val) {
      if (props.operateType === 'add') {
        getKnifeData();
      } else {
        knifeData.value = [props.rowData];
        console.log('knifeData.value', knifeData.value);
      }
      topFormList.value.forEach(item => {
        if (item.tansfromDisabled) {
          item.disabled = item.tansfromDisabled(props.operateType);
        }
      });
      Object.keys(model.value).forEach(item => {
        if (props.rowData) {
          model.value[item] = props.rowData[item];
        } else {
          model.value[item] = model.value[item] ? model.value[item] : null;
        }
      });
    }
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<template>
  <Modal
    v-model:visible="modelVisible"
    :title="`${{ add: '新增', edit: '编辑', look: '查看' }[props.operateType]}刀具数据记录表`"
    height="70vh"
    width="75vw"
    :destroy-on-close="true"
    :centered="true"
    @close="handleClose"
  >
    <div class="add-v-cut-tool-record-form">
      <div v-if="props.operateType !== 'add'" class="state">
        <template v-if="props.rowData.state === 0">
          <img :src="unaudited" alt="examine-icon" />
        </template>
        <template v-if="props.rowData.state === 2 || props.rowData.state === 4">
          <img :src="underReview" alt="examine-icon" />
        </template>
        <template v-if="props.rowData.state === 3">
          <img :src="audited" alt="examine-icon" />
        </template>
      </div>

      <!-- 新增表单 -->
      <ATabs>
        <ATabPane key="1" tab="基本信息"></ATabPane>
      </ATabs>
      <div>
        <ATable
          :columns="columns"
          :pagination="false"
          :data-source="knifeData"
          :loading="loading"
          size="small"
          bordered
          row-key="id"
          :scroll="{ x: 'auto', y: 'auto' }"
        />
      </div>
      <Form ref="topFormRef" v-model:model="model" :form-list="topFormList"></Form>
    </div>
    <template #footer>
      <div class="modal-footer">
        <AButton v-if="props.operateType == 'add'" type="primary" :loading="modleAddLoading" @click="handleOk('add')">
          保 存
        </AButton>
        <AButton v-if="props.operateType == 'edit'" type="primary" :loading="modleAddLoading" @click="handleOk('edit')">
          修 改
        </AButton>
        <AButton @click="handleClose">关 闭</AButton>
      </div>
    </template>
  </Modal>
  <div class="fonttips">备注：V-CUT刀程要求：60000米需研磨，新刀直径120+0.8MM　旧刀直径低于115MM 报废处理！</div>
</template>

<style lang="scss" scoped>
.fonttips {
  font-size: larger;
  font-weight: 500;
  color: red;
}
.add-v-cut-tool-record-form {
  border: 1px solid #ccc;
  padding: 0 30px;
  overflow: auto;
  position: relative;
  padding-top: 36px;
  padding-bottom: 15px;
  .state {
    position: absolute;
    top: 0;
    right: 100px;
    img {
      height: 80px;
    }
  }
}
</style>
